<template>
  <view class="mian">
    <view class="topimg">
      <image src="../../static/img/boxlink/boxlink.png" mode=""></image>
    </view>
    <view class="dropBox">
      <view class="left flex padding">
        <image src="../../static/img/boxlink/boy.png" mode="scaleToFill" />
        <button
          type="default"
          @click="toggle('center', 1)"
          :loading="loading"
          plain
        >
          抽一张纸条
        </button>
        <button
          type="default"
          @click="toggle('bottom', 1)"
          :loading="loading"
          plain
        >
          放一张纸条
        </button>
      </view>
      <view class="right flex padding">
        <image src="../../static/img/boxlink/gril.png" mode="scaleToFill" />
        <button
          type="default"
          @click="toggle('center', 0)"
          :loading="loading"
          plain
        >
          抽一张纸条
        </button>
        <button
          type="default"
          @click="toggle('bottom', 0)"
          :loading="loading"
          plain
        >
          放一张纸条
        </button>
      </view>
    </view>

    <uni-popup ref="popup" background-color="#fff">
      <view
        class="popup-content"
        :class="{ 'popup-height': type === type }"
        v-if="type === 'bottom'"
      >
        <uni-section title="真实有效的信息更容易被抽取" type="line" />
        <uni-card title="选择你的自拍或生活照" extra="">
          <view class="uni-body"
            ><view class="writeMess">
              <uni-file-picker
                limit="3"
                title=""
                v-model="chooseImageUrl"
              ></uni-file-picker> </view
          ></view>
        </uni-card>

        <view class="form">
          <uni-card title="信息填写" extra="">
            <view class="uni-body">
              <uni-forms
                ref="valiForm"
                :rules="rules"
                :modelValue="valiFormData"
              >
                <uni-forms-item label="微信" required name="name">
                  <uni-easyinput
                    v-model="valiFormData.weixinNunber"
                    placeholder="请输入微信号"
                  />
                </uni-forms-item>
                <uni-forms-item label="年龄" required name="age">
                  <uni-easyinput
                    v-model="valiFormData.age"
                    placeholder="请输入年龄"
                  />
                </uni-forms-item>
                <uni-forms-item label="关于我" name="introduction">
                  <uni-easyinput
                    type="textarea"
                    v-model="valiFormData.introduction"
                    placeholder="请输入自我介绍"
                  />
                </uni-forms-item>
              </uni-forms>
              <button type="primary" @click="submit()">投放纸条</button>
            </view>
          </uni-card></view
        >
      </view>

      <view
        class="popup-content"
        :class="{ 'popup-height': type === type }"
        v-if="type === 'center'"
      >
        <uni-card
          title="纸条内容"
          :extra="
            new Date(parseInt(draw_list.date))
              .toLocaleString()
              .replace(/:\d{1,2}$/, ' ')
          "
        >
          <view class="uni-body">
            <view class="mes">
              <view class="wexin">
                微信: <span>{{ draw_list.weixinNumber }}</span>
              </view>
              <view class="inter">
                关于我: <span>{{ draw_list.introduction }} </span></view
              >
              <view class="age">
                年龄: <span>{{ draw_list.age }}</span>
              </view>
              <view class="sex"
                >性别: <span>{{ draw_list.sex == 0 ? "女" : "男" }}</span></view
              >
            </view>
            <view class="img">
              <view
                class="item"
                v-for="item in draw_list.imgList"
                :key="item"
                @click="preViewImg"
              >
                <image :src="item" mode="scaleToFill" />
              </view>
            </view>
            <view class="btnGroup">
              <button type="primary" class="plain" plain="true" @click="copy()">
                不喜欢
              </button>
              <button type="primary" @click="copy(draw_list.weixinNumber)">
                复制微信
              </button>
            </view>
          </view>
        </uni-card>
      </view>
    </uni-popup>

    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog
        type="error"
        cancelText="取消"
        confirmText="确定"
        title="提示"
        content="您未登录, 请先登录"
        @confirm="dialogConfirm"
        @close="dialogClose"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref } from "vue";
import useClipboard from "vue-clipboard3";
const { toClipboard } = useClipboard();

const loading = ref(false);
const popup = ref(null);
const alertDialog = ref(null);
const type = ref("bottom");
const chooseImageUrl = ref([]);
const imgList = ref([]);

const db = uniCloud.database();

// 校验表单
// 校验规则
const rules = ref({
  name: {
    rules: [
      {
        required: true,
        errorMessage: "姓名不能为空",
      },
    ],
  },
  age: {
    rules: [
      {
        required: true,
        errorMessage: "年龄不能为空",
      },
      {
        format: "number",
        errorMessage: "年龄只能输入数字",
      },
    ],
  },
});

const valiFormData = ref({
  weixinNunber: "",
  chooseImage: "",
  introduction: "",
  sex: 1,
});

const valiForm = ref(null);
const submit = () => {
  valiForm.value
    .validate()
    .then((res) => {
      if (chooseImageUrl.value.length < 3) {
        return uni.showToast({
          title: "最少选三张图片",
          icon: "none",
          mask: true,
        });
      }
      // 表单校验通过开始提交数据
      uni.showLoading({
        title: "加载中...",
      });
      let imgList = [];
      chooseImageUrl.value.map((item) => {
        imgList.push(item.fileID);
      });
      db.collection("blind_box_list")
        .add({
          imgList: imgList,
          weixinNumber: valiFormData.value.weixinNunber,
          age: valiFormData.value.age,
          introduction: valiFormData.value.introduction,
          sex: valiFormData.value.sex,
          date: new Date().getTime(),
        })
        .then(() => {
          uni.showToast({
            title: "投放成功",
          });
          popup.value.close();
        })
        .catch(() => {
          uni.showToast({
            title: "投放失败, 请检查网络",
            icon: "none",
            mask: true,
          });
        });
    })
    .catch((err) => {
      uni.showToast({
        title: "少填东西了",
        icon: "none",
        mask: true,
      });
    });
};

// 图片预览
const preViewImg = () => {
  uni.previewImage({
    urls: draw_list.value.imgList,
    longPressActions: {
      itemList: ["保存图片"],
    },
  });
};

// 显示弹出层
const draw_list = ref("");
const toggle = async (types, sex) => {
  type.value = types;
  valiFormData.value.sex = sex;

  if (uni.getStorageSync("uni_id_token")) {
    if (types == "center") {
      uni.showLoading({
        title: "加载中...",
      });
      // 中间弹出层就随机查询
      const res = await db
        .collection("blind_box_list")
        .aggregate()
        .match({
          sex: sex,
        })
        .sample({
          size: 2,
        })
        .end()
        .catch(() => {
          return uni.showToast({
            title: "抽取失败, 请检查网络",
            icon: "none",
            mask: true,
          });
        });
      uni.hideLoading();
      draw_list.value = res.result.data[0];
      console.log(draw_list.value);
    }
    popup.value.open(type.value);
  } else {
    alertDialog.value.open();
  }
};

const copy = (value) => {
  if (!value) {
    popup.value.close();
    return;
  }
  try {
    toClipboard(value);
    uni.showToast({
      title: "复制成功",
    });
  } catch (e) {}
};

// 对话框点击确认
const dialogConfirm = () => {
  uni.navigateTo({
    url: "/pages/ucenter/login-page/pwd-login/pwd-login",
  });
};

// 对话框点击取消
const dialogClose = () => {
  return;
};
</script>

<style lang="scss" scoped>
.topimg {
  image {
    width: 100%;
    height: 300rpx;
  }
}
.dropBox {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .flex {
    display: flex;
    align-items: center;
    justify-content: space-around;
    flex-direction: column;
  }
  button {
    margin-top: 20rpx;
  }
  .left {
  }
  .right {
  }

  .padding {
    padding: 40rpx;
  }

  image {
    width: 300rpx;
    height: 300rpx;
  }
}
.popup-content {
  padding-bottom: 50rpx;

  .writeMess {
  }

  .form {
    button {
      background-color: #fe78a1;
    }
  }
}

.popup-content {
  .mes { 
    span { 
      color: black;
    }
  }
  .img {
    display: flex;
    .item {
      padding: 10rpx;
    }
    image {
      width: 200rpx;
      height: 200rpx;
    }
  }

  .btnGroup {
    display: flex;
    padding-top: 50rpx;
    padding-bottom: 20rpx;
    button {
      background-color: #fe78a1;
      width: 47%;
      height: auto;
    }

    .plain {
      background-color: #fff;
      color: #fe78a1;
      border: #fe78a1 solid 1rpx;
    }
  }
}
</style>
